const express = require("express")
const fs = require("fs")
const {getHtml} = require("../../utils/markdown")
const {queryArticle} = require("../../dao")

const router = express.Router()

const defaultValue = {
    "id": "无",
    "article": "无",
    "label": "无",
    "title": "无",
    "author": "Sylvie无",
    "imgUrl": "/xxx",
    "like": 0,
    "comment": 0,
    "look": 0,
    "time": "2021-9-20",
    "article_path": "/xxx",
    "classify": "top|new|acg|game"
}

// 处理/article/:id的请求
router.get("/:id", async (req, resp) => {
    // console.log("获取的id: " + req.params.id)
    let result
    try {
        result = (await queryArticle(req.params.id))[0]
    } catch (error) {
        console.log("article query 错误")
        result = defaultValue
        result.article_content = "<h1>请求错误</h1>"
        return resp.json(result)
    }
    // console.log(result)
    // console.log(result.article_path)

    // 读取markdown文章
    let text = fs.readFileSync(result.article_path).toString("utf-8")

    // 装换为HTML 
    let html = getHtml(text)
    // console.log(html)

    // 放入响应体中
    result.article_content = html

    // 以JSON格式发送回去
    resp.json(result)
})

module.exports = router